package q695;

/**
 * 695. 岛屿的最大面积
 */
public class Solution {

    int maxArea = 0;

    public int maxAreaOfIsland(int[][] grid) {
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (judge(grid, i, j)) {
                    maxArea = Math.max(dfs(grid, i, j), maxArea);
                }
            }
        }
        return maxArea;
    }

    public int dfs(int[][] grid, int i, int j) {
        if (!judge(grid, i, j)) return 0;
        grid[i][j] = 2;
        int area = 1;
        area += dfs(grid, i - 1, j);
        area += dfs(grid, i + 1, j);
        area += dfs(grid, i, j - 1);
        area += dfs(grid, i, j + 1);
        return area;
    }

    public boolean judge(int[][] grid, int i, int j) {
        return i >= 0 && j >= 0 && i < grid.length && j < grid[i].length && grid[i][j] == 1;
    }
}
